﻿using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Collections.Generic;

namespace TN_CMS.Domain
{
    public static class DatabaseExtension
    {
        public static IDataReader ExecuteStoreProcedureReader(this Database db, string storedProcedureName, CommandBehavior commandBehavior, params DbParameter[] parameters)
        {
            DbConnection conn = db.CreateConnection();
            using (DbCommand comm = conn.CreateCommand())
            {
                comm.CommandType = CommandType.StoredProcedure;
                comm.CommandText = storedProcedureName;
                if (parameters != null)
                {
                    foreach (DbParameter parameter in parameters)
                    {
                        comm.Parameters.Add(parameter);
                    }
                }
                conn.Open();
                return comm.ExecuteReader(commandBehavior);
            }
        }

        public static IEnumerable<TResult> Execute<TResult>(this Database db, string storedProcedureName, IRowMapper<TResult> map, params DbParameter[] parameters)
        {
            var result = new List<TResult>();
            using (var reader = db.ExecuteStoreProcedureReader(storedProcedureName, CommandBehavior.CloseConnection, parameters))
            {
                while (reader.Read())
                {
                    result.Add(map.MapRow(reader));
                }
            }

            return result;
        }

        public static DbParameter CreateParameter(this Database db, string name, object value = null, DbType type = DbType.Object, ParameterDirection parameterDirection = ParameterDirection.Input)
        {
            DbParameter result = db.DbProviderFactory.CreateParameter();
            if (result != null)
            {
                result.ParameterName = db.BuildParameterName(name);
                result.Value = value;
                result.DbType = type;
                result.Direction = parameterDirection;
            }
            return result;
        }
    }
}